package com.fileChooser;

import java.io.File;
import java.util.*;

import android.app.*;
import android.content.*;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Toast;

import com.mobilnaElka.activities.R;
import com.mobilnaElka.activities.calendar.CalendarSettingsActivity;

public class FileChooser {

	public static final int DIALOG_FILES = 0;
	private File currentDir;
	private FileArrayAdapter adapter;
	private Context context;
	private String chosenFilePath;

	public FileChooser(Bundle savedInstanceState, Context context) {
		currentDir = new File("/sdcard/");
		this.context=context;
		fill(currentDir);
	}

	  public Dialog onCreateDialog(int id) {
	    switch (id) {
	      case DIALOG_FILES:
	        AlertDialog.Builder builder = new AlertDialog.Builder(context);
	        builder.setTitle(R.string.choose_file);
	        builder.setAdapter(adapter, fileSelected);
	        return builder.create();
	    }
	    return null;
	  }
	 
	 private OnClickListener fileSelected = new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int which) {
				Option o=adapter.getItem(which);
	        	  if (o.getData().equalsIgnoreCase("folder")
	      				|| o.getData().equalsIgnoreCase("parent directory")) {
	      			currentDir = new File(o.getPath());
	      			fill(currentDir);
	      			Dialog d = onCreateDialog(DIALOG_FILES);
	      			d.setOwnerActivity((Activity) context);
	      			d.show();
	      		} else {
	      			onFileClick(o);
	      		}
				
			}
		};

	private void fill(File f) {
		File[] dirs = f.listFiles();
		List<Option> dir = new ArrayList<Option>();
		List<Option> fls = new ArrayList<Option>();
		try {
			for (File ff : dirs) {
				if (ff.isDirectory())
					dir.add(new Option(ff.getName(), "Folder", ff
							.getAbsolutePath()));
				else {
					String ext=ff.getName().substring(ff.getName().indexOf(".")+1);
					if (ext.equals("html") || ext.equals("htm"))
						fls.add(new Option(ff.getName(), "File Size: "
							+ ff.length(), ff.getAbsolutePath()));
				}
			}
		} catch (Exception e) {

		}
		Collections.sort(dir);
		Collections.sort(fls);
		dir.addAll(fls);
		if (!f.getName().equalsIgnoreCase("sdcard"))
			dir.add(0, new Option("..", "Parent Directory", f.getParent()));
		adapter = new FileArrayAdapter(context,
				R.layout.file_view, dir);
	}

	private void onFileClick(Option o) {
		Toast.makeText(context, "File Clicked: " + o.getName(), Toast.LENGTH_SHORT)
				.show();
		chosenFilePath = o.getPath();
		((CalendarSettingsActivity) context).setChosenFile(chosenFilePath);
		
	}

	public void onBackPressed() {
		currentDir = currentDir.getParentFile();
		if (currentDir.canRead())
			fill(currentDir);
	}

	public void showDialog() {
		onCreateDialog(DIALOG_FILES).show();
		
	}
}
